﻿using System;
using System.Linq;
using System.Collections.Generic;
using Web7.Domain;

namespace Web7.Domain.Page.Extensions
{
    public static class QueryableExtensions
    {
        public static IPagedList<T> GetPage<T>(this IEnumerable<T> query, PagingInfo pagingInfo)
        {
            if (pagingInfo.SkipTop < 1)
                return new PagedList<T>(query.Skip(pagingInfo.Index * pagingInfo.Size).Take(pagingInfo.Size), pagingInfo.Index, pagingInfo.Size, query.Count());
            else
            {
                // 跳过的记录数
                int skipTop = pagingInfo.SkipTop;

                // 跳过的页数
                int skipPage = (int)Math.Floor((double)skipTop / pagingInfo.Size);

                // 如果目标页数在跳过的页数范围内，不从数据库中提取数据
                if (skipPage > pagingInfo.Index)
                    return new PagedList<T>(Enumerable.Empty<T>(), pagingInfo.Index, pagingInfo.Size, query.Count() + skipTop);

                // 第一页真实记录数
                int realSize = pagingInfo.Size - skipTop % pagingInfo.Size;

                if (skipPage == pagingInfo.Index)
                {
                    return new PagedList<T>(query.Skip(0).Take(realSize), pagingInfo.Index, pagingInfo.Size, query.Count() + skipTop);
                }
                else
                {
                    return new PagedList<T>(query.Skip((pagingInfo.Index - skipPage) * pagingInfo.Size - realSize).Take(pagingInfo.Size), pagingInfo.Index, pagingInfo.Size, query.Count() + skipTop);
                }

            }
        }
    }
}